import { useEffect, useMemo } from "react"
import {useVisionStore} from '@/pages/index'

import DynamicDiscern from "./DynamicDiscern"
import DynamicDrop from "./DynamicDrop"
const eventType = ['click', 'mousemove', 'mousedown', 'mouseup']

class EventCtr{
  eventlist:any = {}
  constructor() {
    this.init()
  }
  init() {
    eventType.forEach((type) => {
      this.eventlist[type] = {}
    });
  }
  startEvent() {
    eventType.forEach((type) => {
      this.addEventListener(document.getElementById('root'), type);
    });
  }
  addQueue(type: any,{callBack, code, ...option}: any) {
    if(!this.eventlist[type][code]) {
      this.eventlist[type][code] = []
    }
    this.eventlist[type][code].push({
      callBack,
      intercept: true,
      ...option
    })
  }
  getEventFnList(type: string) {
    let subList = this.eventlist[type]
    let fn: any[] = []
    Object.keys(subList).forEach(key => {
      fn = fn.concat(subList[key].filter((item: { intercept: boolean }) => item.intercept === false).map((item:any) => item.callBack))
    })
    return fn
  }
  addEventListener(dom: HTMLElement | null, type: string) {
    const thas = this;
    const callBack = (e: any) => {
      const eventFnList = thas.getEventFnList(type);
      eventFnList.forEach((event) => {
        event(e);
      });
    };
    dom!.addEventListener(type, callBack)
  }
  handleToolIntercept(type: string | number, code: string | number, flag: any) {
    this.eventlist[type][code].forEach((item: any) => item.intercept = flag)
  }
}


export default () => {
  const store = useVisionStore();

  useMemo(()=>{
    store.event = new EventCtr()  
  }, [])
  useEffect(()=>{
    store.event.startEvent()
  }, [])

  return (
    <>
      <DynamicDiscern></DynamicDiscern>
      <DynamicDrop/>
    </>
  )
}